package br.com.pfm.controller;

import java.util.Calendar;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import br.com.pfm.dao.ClienteDao;
import br.com.pfm.persistence.model.Cliente;

/**
 * Handles requests for the application home page.
 */
@Transactional
@Controller
public class LoginController {
	
	@Autowired
	ClienteDao clienteDao;
	
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	@RequestMapping(value = "/loginForm")
	public String loginForm(Model model) {
		logger.info("Abrindo login form");
					
		return "login/formulario-login";
	}
	
	@RequestMapping(value = "/efetuaLogin",method = RequestMethod.POST)
	public String efetuaLogin(Model model, HttpSession session, @RequestParam String login, @RequestParam String senha) {
		logger.info("Tentando logar");
		
		Cliente cliente = clienteDao.findCliente(login, senha);
		
		if(cliente != null){
			session.setAttribute("clienteLogado", cliente);
			
			int ano = Calendar.getInstance().get(Calendar.YEAR);
			int mes = Calendar.getInstance().get(Calendar.MONTH) +1;
			
			session.setAttribute("anoCorrente", ano);
			session.setAttribute("mesCorrente", mes);
			
			
			
			return "redirect:/poslogin";
		}
		
		return "redirect:/loginForm";		
	}

	@RequestMapping("/logout")
	public String logout(HttpSession session) {
	  session.invalidate();
	  return "redirect:loginForm";
	}

}
